import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// 路由懒加载方式
const Tabbar = () => import('@/components/app-tabbar.vue')
const Home = () => import('@/views/home/index.vue')
const Question = () => import('@/views/question')
const Video = () => import('@/views/video')
const User = () => import('@/views/user')
const Article = () => import('@/views/article')
const Login = () => import('@/views/login')
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    components: {
      default: Home,
      tabbar: Tabbar
    }
  },
  {
    path: '/question',
    components: {
      default: Question,
      tabbar: Tabbar
    }
  },
  {
    path: '/video',
    components: {
      default: Video,
      tabbar: Tabbar
    }
  },
  {
    path: '/user',
    components: {
      default: User,
      tabbar: Tabbar
    }
  },
  {
    path: '/article',
    component: Article
  },
  {
    path: '/login',
    component: Login
  }
]

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch((err) => err)
}
const router = new VueRouter({
  mode: 'hash', // 配置路由模式, hash/history
  routes
})
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  // 如果没有token && 去的页面的路径包含 /user
  if (!token && to.path.startsWith('/user')) {
    return next(`/login?returnUrl=${encodeURIComponent(router.currentRoute.fullPath)}`)
  }
  // 直接放行
  next()
})

export default router
